/*
 * Copyright (c) 2020 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.zhihu.matisse.library.utils;

import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.media.image.ImageSource;

import ohos.utils.net.Uri;

import java.io.*;

/**
 * @author wallace
 */
public class UriUtils {

    private static final String SCHEME_DATA = "dataability";
    private static final String SCHEME_FILE = "file";
    private static final String SCHEME_HTTP = "http";
    private static final String SCHEME_HTTPS = "https";

    public static ImageSource uriToImageSource(Context context, Uri uri){
        ImageSource.SourceOptions options = new ImageSource.SourceOptions();
        if (isDataMediaUri(uri)) {
            return ImageSource.create(uriToInputStream(context, uri), options);
        } else if (isResourceUri(context, uri)) {
            return ImageSource.create(uriToResource(context, uri), options);
        } else if (isNetWorkUri(uri)) {
            return null;
        } else if (isFileUri(uri)) {
            return ImageSource.create(uriToFileInputStream(uri), options);
        }else if (isAssertUri(uri)) {
            return ImageSource.create(uriRawFile(context,uri), options);
        } else {
            return null;
        }
    }

    /**
     *
     * @param uri dataability:///media/***
     */
    public static boolean isDataMediaUri(Uri uri){
        if (uri.getDecodedPathList() != null){
            if (uri.getDecodedPathList().size() > 0){
                return uri.getScheme().equals(SCHEME_DATA) && uri.getEncodedAuthority().isEmpty() && uri.getDecodedPathList().get(0).equals("media");
            }else {
                return false;
            }
        }else {
            return false;
        }
    }

    /**
     *
     * @param uri dataability:///resources/rawfile/...
     */
    public static boolean isAssertUri(Uri uri){
        if (uri.getDecodedPathList() != null){
            if (uri.getDecodedPathList().size() > 2){
                return uri.getScheme().equals(SCHEME_DATA)
                        && uri.getEncodedAuthority().isEmpty()
                        && uri.getDecodedPathList().get(0).equals("resources")
                        && uri.getDecodedPathList().get(1).equals("rawfile");
            }else {
                return false;
            }
        }else {
            return false;
        }
    }

    /**
     *
     * @param uri dataability://bundleName/id
     */
    public static boolean isResourceUri(Context context,Uri uri){
        return uri.getScheme().equals(SCHEME_DATA) && uri.getDecodedAuthority().equals(context.getBundleName());
    }

    /**
     *
     * @param uri http://www.***.com or https://www.***.com
     */
    public static boolean isNetWorkUri(Uri uri){
        return uri.getScheme().equals(SCHEME_HTTP) || uri.getScheme().equals(SCHEME_HTTPS);
    }
    /**
     *
     * @param uri file://...
     */
    public static boolean isFileUri(Uri uri){
        return uri.getScheme().equals(SCHEME_FILE);
    }

    private static FileInputStream uriToFileInputStream(Uri uri) {
        try {
            File file = new File(uri.getDecodedPath());
            return new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static FileDescriptor uriToInputStream(Context context, Uri uri) {
        try {
            return DataAbilityHelper.creator(context).openFile(uri, "r");
        } catch (DataAbilityRemoteException | FileNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }

    private static Resource uriToResource(Context context, Uri uri) {
        try {
            return context.getResourceManager().getResource(Integer.parseInt(uri.getDecodedPath()));
        } catch (NotExistException | IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static Resource uriRawFile(Context context, Uri uri) {
        try {
            RawFileEntry rawFileEntry = context.getResourceManager().getRawFileEntry("resources/rawfile/" + uri.getLastPath());
            return rawFileEntry.openRawFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
